package com.lifeverse.repository;

import com.lifeverse.entity.BehaviorPattern;
import com.lifeverse.entity.enums.PatternStatus;
import com.lifeverse.entity.enums.PatternType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 行为模式数据访问接口
 */
@Repository
public interface BehaviorPatternRepository extends JpaRepository<BehaviorPattern, Long> {

    /**
     * 根据生命体ID查找行为模式
     */
    List<BehaviorPattern> findByLifeEntityId(Long lifeEntityId);

    /**
     * 根据生命体ID和模式类型查找行为模式
     */
    List<BehaviorPattern> findByLifeEntityIdAndPatternType(Long lifeEntityId, PatternType patternType);

    /**
     * 根据模式状态查找行为模式
     */
    List<BehaviorPattern> findByStatus(PatternStatus status);

    /**
     * 查找活跃的行为模式
     */
    @Query("SELECT bp FROM BehaviorPattern bp WHERE bp.status = 'ACTIVE' AND bp.lastDetectedAt >= :since")
    List<BehaviorPattern> findActivePatternsSince(@Param("since") LocalDateTime since);

    /**
     * 根据置信度范围查找模式
     */
    @Query("SELECT bp FROM BehaviorPattern bp WHERE bp.confidenceScore >= :minConfidence AND bp.confidenceScore <= :maxConfidence")
    List<BehaviorPattern> findByConfidenceRange(@Param("minConfidence") Double minConfidence, 
                                               @Param("maxConfidence") Double maxConfidence);

    /**
     * 查找异常模式
     */
    @Query("SELECT bp FROM BehaviorPattern bp WHERE bp.anomalyScore >= :threshold ORDER BY bp.anomalyScore DESC")
    List<BehaviorPattern> findAnomalousPatterns(@Param("threshold") Double threshold);

    /**
     * 根据生命体ID分页查询模式
     */
    Page<BehaviorPattern> findByLifeEntityId(Long lifeEntityId, Pageable pageable);

    /**
     * 查找高频模式
     */
    @Query("SELECT bp FROM BehaviorPattern bp WHERE bp.frequency >= :minFrequency ORDER BY bp.frequency DESC")
    List<BehaviorPattern> findHighFrequencyPatterns(@Param("minFrequency") Integer minFrequency);

    /**
     * 统计生命体的模式数量
     */
    @Query("SELECT COUNT(bp) FROM BehaviorPattern bp WHERE bp.lifeEntityId = :lifeEntityId AND bp.status = :status")
    Long countByLifeEntityIdAndStatus(@Param("lifeEntityId") Long lifeEntityId, @Param("status") PatternStatus status);

    /**
     * 查找需要更新的过期模式
     */
    @Query("SELECT bp FROM BehaviorPattern bp WHERE bp.lastDetectedAt < :expiredBefore AND bp.status != 'EXPIRED'")
    List<BehaviorPattern> findExpiredPatterns(@Param("expiredBefore") LocalDateTime expiredBefore);
}